import React, { PureComponent } from 'react';
import { Form, Input, Table, Button, Select, Icon, notification, Modal } from 'antd';
import StructureTreeSelect from "./structureTreeSelect"
import { connect } from 'dva';
class PierStructures extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            selectActive: true,
            loading: false,
            selectedRowKeys: [],
            data: [],
            extra: {}
        }
        this.addStructures = this.addStructures.bind(this)
        this.onSelect = this.onSelect.bind(this)
        this.getData = this.getData.bind(this)
        this.massEditProp = this.massEditProp.bind(this)
        this.replaceComponent = this.replaceComponent.bind(this)
        this.deleteComponent = this.deleteComponent.bind(this)
        this.massDelete = this.massDelete.bind(this)
        this.refresh = this.refresh.bind(this)
        this.massReplace = this.massReplace.bind(this)
    }

    componentDidMount() {
        if (this.props.onLoaded) {
            this.props.onLoaded(this)
        }
    }
    async componentWillMount() {
        let { pierData } = this.props;
        let typeData = await this.props.getBottomDefinitionTreeList({ bridgeId: pierData.bridgeId, spanId: pierData.id })
        if (typeData && typeData.length) {
            const len=typeData.length
            for (let i = 0; i < len; i++) {
                let item = typeData[i];
                item.title = item.name;
                item.key = item.id;
                item.value = item.id

            }
        }
        this.setState({
            treeData: typeData
        })
        this.getData()
    }
    refresh() {
        this.setState({
            selectedRowKeys:[]
        })
        this.getData()
    }
    async onSelect(keys, e) {
        let { extra } = this.state;
        let { id } = e.props;
        extra.definitionTypeParentId = id;
        await this.setState({
            extra
        })
        this.getData()
    }
    massDelete(e) {
        e.preventDefault()
        Modal.confirm({
            title: "提示",
            content: "是否删除选中构件?",
            okText:"确定",
            cancelText:"取消",
            onOk:()=>{
                let { pierData ,deleteDefinitionInstance,treeContext,goInnerPage} = this.props;
                let { selectedRowKeys, data } = this.state;
                if (selectedRowKeys && selectedRowKeys.length) {
                    let arr = []
                    let sidArr = []
                    const len=selectedRowKeys.length
                    for (let i = 0; i < len; i++) {
                        let item = selectedRowKeys[i];
                        const sid = data.find(unit => unit.id == item)
                        sidArr.push(sid)
                    }
                    let sids = sidArr.map(item => item.sid)
                   deleteDefinitionInstance({ definitionInstanceIds: selectedRowKeys, selectionOrSpanIds: Array.from(new Set(sids)), type: "bottom", bridgeId: pierData.bridgeId }, res => {
                        if (res && res.length) {
                            const len=res.length
                            for (let i = 0; i < len; i++) {
                                const item = res[i];
                                arr.push("botStructureComponentUnit" + item)
                            }
                        }
                        treeContext.removeTreeNode(arr)
                        if (goInnerPage) {
                           goInnerPage(null, 'results', '操作成功')
                        }
                    }, err => {

                    })
                } else {
                    notification.warn({ message: "请选择构件" })
                }
            },
            onCancel() { },
        })
    }
    async getData() {
        let { extra } = this.state;
        this.setState({
            loading: true
        })
        let { pierData } = this.props;
        let res = await this.props.getBotDefinitionInstanceList({ sid: pierData.id, ...extra })
        this.setState({
            data: res,
            loading: false,
        })
    }
    addStructures() {
        let { pierData,modalContext } = this.props;
        pierData.selectedRowKeys=[pierData.id]
        pierData.sid=pierData.id
        pierData.type = "bottom"
        pierData.operateType = "add"
        pierData.nodeType = "4"
       modalContext.updateModal({
            visible: true,
            title: "添加构件",
            event: { code: "structureSelect" },
            extra: pierData
        });
    }
    async editComponentProp(e, item) {
        let selectedRowKeys = [];
        selectedRowKeys.push(item.id)
        e.preventDefault();
        await this.setState({
            selectedRowKeys
        })
        this.massEditProp()
    }
    deleteComponent(e, item) {
        let selectedRowKeys = [item.id]
        e.preventDefault();
        Modal.confirm({
            title: "提示",
            content: "是否删除选中构件?",
            okText:"确定",
            cancelText:"取消",
            onOk:()=>{
                let { pierData,deleteDefinitionInstance,treeContext,goInnerPage } = this.props;
                if (selectedRowKeys && selectedRowKeys.length) {
                   deleteDefinitionInstance({ definitionInstanceIds: selectedRowKeys, type: "bottom", bridgeId: pierData.bridgeId }, res => {
                        let arr = []
                        if (res && res.length) {
                            const len=res.length
                            for (let i = 0; i < len; i++) {
                                const item = res[i];
                                arr.push("botStructureComponentUnit" + item)
                            }
                        }
                        treeContext.removeTreeNode(arr)
                        
                        if (goInnerPage) {
                            goInnerPage(null, 'results', '操作成功')
                        }
                    }, err => {

                    })
                } else {
                    notification.warn({ message: "请选择构件" })
                }
            },
            onCancel() { },
        })
    }
    massEditProp(e) {
        if (e) {
            e.preventDefault();
        }
        let arr = [];
        let arr2 = []
        let { selectedRowKeys, data } = this.state;
        if (selectedRowKeys && selectedRowKeys.length) {
            const len=selectedRowKeys.length
            for (let i = 0; i < len; i++) {
                const item = selectedRowKeys[i];
                const obj = data.find(item2 => item2.id == item)
                arr.push(obj.definitionTreeId)
                arr2.push(obj.sid)
            }
            let same = !arr.some(function (value, index) {
                return value != arr[0];
            });
            if (!same) {
                notification.warn({ message: "只能选择同类构件!" })
                return;
            } else {
                let obj = data.find(item => item.id == selectedRowKeys[0]);
                obj.selectedRowKeys = selectedRowKeys;
                obj.unitids = arr2;
                this.props.goInnerPage(null, 'componentEdit', obj.definitionType, obj)
            }
        } else {
            notification.warn({ message: "请至少选择一个构件!" })
            return;
        }
    }
    massReplace(e) {
        e.preventDefault()
        let definitionTreeLevel;
        let { pierData,modalContext } = this.props;
        let { selectedRowKeys, data } = this.state;
        let arr = [],arr2 = [],arr3 = [],arr4 = [],arr5 = [],arr6=[];
        if (selectedRowKeys && selectedRowKeys.length) {
            const len=selectedRowKeys.length
            for (let i = 0; i < len; i++) {
                let item = selectedRowKeys[i];
                const len2=data.length
                for (let j = 0; j < len2; j++) {
                    let item2 = data[j];
                    if (item2.id == item) {
                        arr.push(item2.definitionTreeId);
                        arr2.push(item2.sid);
                        arr3.push(item2.id)
                        arr4.push(item2.definitionId)
                        arr5.push(item2)
                        arr6.push(item2.number)
                        definitionTreeLevel = item2.definitionTreeLevel
                    }
                }
            }
            let same = !arr.some(function (value, index) {
                return value != arr[0];
            });
            if (!same) {
                notification.warn({ message: "只能选择同类构件!" })
                return;
            }
            if (modalContext) {
                modalContext.updateModal({
                    visible: true,
                    title: "替换构件",
                    event: { code: "structureSelect" },
                    extra: {
                        sid: arr2,
                        definitionTreeIds: arr,
                        definitionTemps: Array.from(new Set([...arr4])),
                        originalData: arr5,
                        "nodeType": 4,
                        definitionTreeLevel,
                        definitionIds: arr3,
                        tid:arr[0],
                        spanType:arr6[0].split("")[0],
                        type: "bottom",
                        operateType: "update",
                        bridgeId: pierData.bridgeId
                    }
                });
            }
        } else {
            notification.warn({ message: "请选择构件!" })
        }
    }
    replaceComponent(e, item) {
        if (e) {
            e.persist();
            e.preventDefault()
        }
        let { pierData, modalContext} = this.props
        let definitionIds = [item.id]
        if (modalContext) {
           modalContext.updateModal({
                visible: true,
                title: "替换构件",
                event: { code: "structureSelect" },
                extra: {
                    sid: item.sid,
                    definitionTreeIds: [item.definitionTreeId],
                    definitionTemps: [item.definitionId],
                    originalData: [item],
                    "nodeType": 4,
                    definitionIds,
                    type: "bottom",
                    tid:item.definitionTreeId,
                    spanType:item.number.split('')[0],
                    definitionTreeLevel: item.definitionTreeLevel,
                    operateType: "update",
                    bridgeId: pierData.bridgeId
                }
            });
        }
    }
    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys });
    };

    render() {
        const { pierData, commondShow } = this.props;
        const { data, selectActive, selectedRowKeys, loading, treeData } = this.state;
        const { getFieldDecorator } = this.props.form;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const columns = [
            {
                title: '构件名称',
                dataIndex: 'instanceName',
            },
            {
                title: '构件类型',
                dataIndex: 'definitionType',
            },
            {
                title: '桩号',
                dataIndex: 'code',
            },
            {
                title: '墩号',
                dataIndex: 'number',
            },
            {
                title: '编辑构件',
                key: 'action',
                width: "260px",
                render: (text, record) => <span className="operate"><a onClick={(e) => this.replaceComponent(e, record)}><Icon type="retweet" /><span>构件替换</span></a> <a onClick={(e) => this.editComponentProp(e, record)}><Icon type="edit" /><span>属性编辑</span></a> <a onClick={(e) => this.deleteComponent(e, record)}><Icon type="delete" /><span>删除构件</span></a></span>,
            },
        ];
        return (
            <div className="pierComponentsBox">
                <Form style={{ padding: "15px" }} labelCol={{ span: 9 }}
                    wrapperCol={{ span: 15 }}>

                    <div>
                        <Form.Item label='桩号'>
                            {getFieldDecorator('designStage', {
                                rules: [
                                    { required: true, message: '桩号' }
                                ],
                                initialValue: pierData ? pierData.code : undefined
                            })(
                                <Input disabled placeholder="桩号"></Input>
                            )}
                        </Form.Item>
                        <Form.Item label='构件类型'>
                            {getFieldDecorator('designStage', {
                                rules: [
                                    { required: true, message: '构件类型' }
                                ]
                            })(
                                <StructureTreeSelect onSelect={this.onSelect} treeData={treeData} onLoaded={(context) => {
                                    this.setState({
                                        structureTreeSelectContext: context
                                    })
                                }}></StructureTreeSelect>
                            )}
                        </Form.Item>
                    </div>
                    <div className="btnBox"><Button onClick={this.addStructures}>添加构件</Button><Button disabled={!selectedRowKeys.length} onClick={this.massEditProp}>编辑属性</Button><Button disabled={!selectedRowKeys.length} onClick={this.massReplace}>构件替换</Button><Button disabled={!selectedRowKeys.length} onClick={this.massDelete}>删除构件</Button></div>
                </Form>
                <div className="tableBox">
                    <Table loading={loading} scroll={{ y: commondShow ? 280 : 360 }} pagination={false} rowSelection={selectActive ? rowSelection : false} rowKey={record => record.id} loading={loading} columns={columns} dataSource={data} />
                </div>
            </div>
        )
    }
}
export default connect(
    ({ }) => ({}),
    dispatch => ({
        getBotDefinitionInstanceList: (values) => dispatch({
            type: 'structure/getBottomDefinitionInstanceList',
            payload: values
        }),
        getBottomDefinitionTreeList: (values) => dispatch({
            type: 'structure/getBottomDefinitionTreeList',
            payload: values
        }),
        deleteDefinitionInstance: (values, onSuccess, onError) => dispatch({
            type: 'structure/deleteDefinitionInstance',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
    })
)(Form.create('PierStructures', {

})(PierStructures))